<template>
  <div class="register-container">
    <div class="register-wrapper">
      <div class="register-card">
        <!-- 头部 -->
        <div class="register-header">
          <div class="logo">
            <img src="/logo.svg" alt="Logo" />
          </div>
          <h2 class="title">用户注册</h2>
          <p class="subtitle">创建您的账户，开始精彩旅程</p>
        </div>

        <!-- 注册表单 -->
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          size="large"
          label-position="top"
          class="register-form"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="registerForm.userName"
              placeholder="请输入用户名（3-20字符，字母数字下划线）"
              clearable
              :prefix-icon="User"
            />
          </el-form-item>

          <!-- 昵称 -->
          <el-form-item label="昵称" prop="nickName">
            <el-input
              v-model="registerForm.nickName"
              placeholder="请输入昵称（2-20字符）"
              clearable
              :prefix-icon="UserFilled"
            />
          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（6-20字符）"
              show-password
              clearable
              :prefix-icon="Lock"
              @input="onPasswordChange"
            />
            <div v-if="passwordStrengthTip" class="password-strength">
              {{ passwordStrengthTip }}
            </div>
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
              clearable
              :prefix-icon="Lock"
            />
          </el-form-item>

          <!-- 邮箱 -->
          <el-form-item :label="emailLabel" prop="email">
            <el-input
              v-model="registerForm.email"
              :placeholder="emailPlaceholder"
              clearable
              :prefix-icon="Message"
            />
          </el-form-item>

          <!-- 邮箱验证开关 -->
          <el-form-item v-if="registerForm.email">
            <el-checkbox
              v-model="showEmailVerification"
              @change="onEmailVerificationChange"
            >
              启用邮箱验证（推荐）
            </el-checkbox>
          </el-form-item>

          <!-- 邮箱验证码 -->
          <el-form-item
            v-if="showEmailVerification"
            label="邮箱验证码"
            prop="emailVerificationCode"
          >
            <div class="verification-input">
              <el-input
                v-model="registerForm.emailVerificationCode"
                placeholder="请输入6位验证码"
                clearable
                :prefix-icon="Key"
                maxlength="6"
              />
              <el-button
                type="primary"
                :disabled="!canSendCode || sendCodeLoading"
                :loading="sendCodeLoading"
                class="send-code-btn"
                @click="sendVerificationCode"
              >
                {{ sendCodeText }}
              </el-button>
            </div>
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item label="手机号" prop="phonenumber">
            <el-input
              v-model="registerForm.phonenumber"
              placeholder="请输入手机号"
              clearable
              :prefix-icon="Phone"
              maxlength="11"
            />
          </el-form-item>

          <!-- 性别 -->
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="registerForm.sex">
              <el-radio :value="'1'">男</el-radio>
              <el-radio :value="'0'">女</el-radio>
              <el-radio :value="'2'">保密</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 邮箱验证选项 -->
          <el-form-item>
            <el-checkbox v-model="showEmailVerification">
              启用邮箱验证（推荐）
            </el-checkbox>
          </el-form-item>

          <!-- 注册按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="registerLoading"
              :disabled="registerLoading"
              class="register-btn"
              @click="handleRegister"
            >
              {{ registerLoading ? "注册中..." : "立即注册" }}
            </el-button>
          </el-form-item>

          <!-- 登录链接 -->
          <div class="login-link">
            <span>已有账户？</span>
            <router-link to="/user/login" class="link"> 立即登录 </router-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import {
  User,
  UserFilled,
  Lock,
  Message,
  Phone,
  Key
} from "@element-plus/icons-vue";
import {
  userRegisterApi,
  sendVerificationCodeApi,
  UserAuthUtils,
  VerificationType,
  type UserRegisterRequest
} from "@/api/user-auth";

defineOptions({
  name: "UserRegister"
});

const router = useRouter();

// 表单引用
const registerFormRef = ref<FormInstance>();

// 表单数据
const registerForm = reactive<UserRegisterRequest>({
  userName: "",
  password: "",
  confirmPassword: "",
  nickName: "",
  email: "",
  phonenumber: "",
  sex: "2",
  emailVerificationCode: "",
  requireEmailVerification: false
});

// 状态管理
const registerLoading = ref(false);
const sendCodeLoading = ref(false);
const showEmailVerification = ref(false);
const countdown = ref(0);
const countdownTimer = ref<NodeJS.Timeout>();

// 计算属性
const passwordStrengthTip = computed(() => {
  if (!registerForm.password) return "";
  return UserAuthUtils.getPasswordStrengthTip(registerForm.password);
});

const canSendCode = computed(() => {
  return (
    UserAuthUtils.validateEmail(registerForm.email) && countdown.value === 0
  );
});

const sendCodeText = computed(() => {
  if (countdown.value > 0) {
    return `${countdown.value}秒后重发`;
  }
  return "发送验证码";
});

const emailLabel = computed(() => {
  return "邮箱";
});

const emailPlaceholder = computed(() => {
  return "请输入邮箱地址";
});

// 表单验证规则
const registerRules = computed<FormRules>(() => ({
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!UserAuthUtils.validateUserName(value)) {
          callback(new Error("用户名格式不正确（3-20字符，字母数字下划线）"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  nickName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!UserAuthUtils.validateNickName(value)) {
          callback(new Error("昵称长度应为2-20字符"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!UserAuthUtils.validatePassword(value)) {
          callback(new Error("密码长度应为6-20字符"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (
          !UserAuthUtils.validatePasswordMatch(registerForm.password, value)
        ) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!UserAuthUtils.validateEmail(value)) {
          callback(new Error("邮箱格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  phonenumber: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!UserAuthUtils.validatePhoneNumber(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  emailVerificationCode: [
    {
      validator: (_rule, value, callback) => {
        // 只有在启用邮箱验证时才需要验证码
        if (showEmailVerification.value) {
          if (!value) {
            callback(new Error("请输入邮箱验证码"));
          } else if (!UserAuthUtils.validateVerificationCode(value)) {
            callback(new Error("请输入6位数字验证码"));
          } else {
            callback();
          }
        } else {
          // 未启用邮箱验证时，验证码字段总是通过验证
          callback();
        }
      },
      trigger: "blur"
    }
  ]
}));

// 密码变化处理
const onPasswordChange = () => {
  // 触发确认密码验证
  if (registerForm.confirmPassword) {
    registerFormRef.value?.validateField("confirmPassword");
  }
};

// 邮箱验证开关变化处理
const onEmailVerificationChange = (value: boolean) => {
  if (!value) {
    // 关闭邮箱验证时，清空验证码
    registerForm.emailVerificationCode = "";
    // 停止倒计时
    if (countdownTimer.value) {
      clearInterval(countdownTimer.value);
      countdown.value = 0;
    }
  }
  // 重新验证邮箱字段
  if (registerForm.email) {
    registerFormRef.value?.validateField("email");
  }
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) return;

  try {
    sendCodeLoading.value = true;

    const response = await sendVerificationCodeApi({
      email: registerForm.email,
      verificationType: VerificationType.REGISTER
    });

    if (response.code === 200) {
      ElMessage.success("验证码已发送到您的邮箱，请查收");
      startCountdown();
    } else {
      ElMessage.error(response.message || "发送验证码失败");
    }
  } catch (error) {
    ElMessage.error(UserAuthUtils.formatErrorMessage(error));
  } finally {
    sendCodeLoading.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  countdownTimer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value);
    }
  }, 1000);
};

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    const valid = await registerFormRef.value.validate();
    if (!valid) return;

    registerLoading.value = true;

    // 准备注册数据
    const registerData: UserRegisterRequest = {
      ...registerForm,
      requireEmailVerification: showEmailVerification.value
    };

    const response = await userRegisterApi(registerData);

    if (response.code === 200) {
      await ElMessageBox.alert(
        "注册成功！您可以使用新账户登录了。",
        "注册成功",
        {
          confirmButtonText: "去登录",
          type: "success"
        }
      );

      // 跳转到登录页面
      router.push("/user/login");
    } else {
      ElMessage.error(response.message || "注册失败");
    }
  } catch (error) {
    ElMessage.error(UserAuthUtils.formatErrorMessage(error));
  } finally {
    registerLoading.value = false;
  }
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 640px) {
  .register-container {
    padding: 16px;
  }

  .register-card {
    padding: 24px;
  }

  .register-header {
    margin-bottom: 24px;

    .title {
      font-size: 24px;
    }

    .subtitle {
      font-size: 14px;
    }
  }

  .verification-input {
    flex-direction: column;

    .send-code-btn {
      width: 100%;
    }
  }
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .register-card {
    color: #f9fafb;
    background: #1f2937;
  }

  .register-header {
    .title {
      color: #f9fafb;
    }

    .subtitle {
      color: #d1d5db;
    }
  }

  .register-form {
    :deep(.el-form-item__label) {
      color: #e5e7eb;
    }
  }

  .login-link {
    color: #d1d5db;
  }
}

.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.register-wrapper {
  width: 100%;
  max-width: 500px;
}

.register-card {
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgb(0 0 0 / 10%);
}

.register-header {
  margin-bottom: 32px;
  text-align: center;

  .logo {
    margin-bottom: 16px;

    img {
      width: 64px;
      height: 64px;
    }
  }

  .title {
    margin: 0 0 8px;
    font-size: 28px;
    font-weight: 600;
    color: #1f2937;
  }

  .subtitle {
    margin: 0;
    font-size: 16px;
    color: #6b7280;
  }
}

.register-form {
  .el-form-item {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      margin-bottom: 8px;
      font-weight: 500;
      color: #374151;
    }

    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 6px rgb(0 0 0 / 10%);
      }

      &.is-focus {
        box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
      }
    }
  }

  .password-strength {
    margin-top: 4px;
    font-size: 12px;
    color: #6b7280;
  }

  .verification-input {
    display: flex;
    gap: 12px;

    .el-input {
      flex: 1;
    }

    .send-code-btn {
      flex-shrink: 0;
      border-radius: 8px;
    }
  }

  .register-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 500;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    border: none;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 16px rgb(64 158 255 / 30%);
      transform: translateY(-2px);
    }

    &:active {
      transform: translateY(0);
    }

    &.is-loading,
    &.is-disabled {
      box-shadow: none;
      transform: none;
    }
  }

  .login-link {
    margin-top: 24px;
    color: #6b7280;
    text-align: center;

    .link {
      margin-left: 4px;
      font-weight: 500;
      color: #409eff;
      text-decoration: none;

      &:hover {
        color: #337ecc;
        text-decoration: underline;
      }
    }
  }
}
</style>
